# docbook_to_uiddict2013.py
"""Reformat the UID list (Table A-1 PS3.6-2013) from the PS3.6 docbook file (from e.g. standards docs) to Python syntax

   Write the dict elements as:
   UID: (name, type, name_info, is_retired)
   in python format

   name_info is extra information extracted from very long names, e.g.
       which bit size a particular transfer syntax is default for
   is_retired is 'Retired' if true, else is ''
"""
#
# Copyright 2008-2014, Darcy Mason
# This file is part of pydicom.
# See the license.txt file for license information.

part6_filename = "part06.xml"
pydict_filename = "_UID_dict.py"
dict_name = "UID_dictionary"

import bs4 # xml parsing module
import os

def parse_docbook_table(book, caption, empty_field_name="Retired"):
    registry = next(t for t in book.findAll("table") if t.caption.text == caption)
    fields = [x.text.strip() for x in registry.thead.tr.childGenerator() if x.__class__ is bs4.element.Tag]
    fields = [x if x != "" else empty_field_name for x in fields]
    def parserow(fields, row):
        return {k:v for k,v in zip(fields, (x.text.strip().replace(u"\u200b","") for x in row.findAll("td")))}
    attrs = [parserow(fields, row) for row in registry.tbody.findAll("tr")]
    return attrs

part6book = bs4.BeautifulSoup(file(part6_filename))
uid_values = parse_docbook_table(part6book, "UID Values")

of = file(pydict_filename, "wb")

of.write("""
# {pydict_filename}
\"\"\"
Dictionary of UID: (name, type, name_info, is_retired)

\"\"\"
# Auto-generated by {filename}\"\"\"

{dict_name} = {{
""".format(pydict_filename = pydict_filename, filename = os.path.basename(__file__), dict_name = dict_name))
lines = []
for x in uid_values:
    name = x["UID Name"].replace(" & ", " and ")
    is_retired = ""
    name_info = ""
    if "(Retired)" in name:
        name = name.replace("(Retired)", "").strip()
        is_retired = "Retired"
    uid = x["UID Value"].replace(u"\u00ad", "")
    if len(name.split(": ")) == 2:
        name, name_info = name.split(": ")
    name=name.strip()
    lines.append("    '{uid}': ('{name}', '{type}', '{name_info}', '{is_retired}')".format(uid=uid, name=name, name_info=name_info, type=x["UID Type"], is_retired=is_retired))
of.write(",\n".join(lines))
of.write("}\n")